import java.sql.SQLOutput;
import java.util.*;

class MyTimerTask implements Comparable<MyTimerTask> {
	private Runnable runnable;
	private long time;
	public MyTimerTask(Runnable runnable, long delay) {
		this.runnable = runnable;
		this.time = System.currentTimeMillis()+delay;
	}

	public Runnable getRunnable() {
		return runnable;
	}
	public long getTime() {
		return time;
	}

	@Override
	public int compareTo(MyTimerTask o) {
		return (int) (this.time-o.getTime());
	}
}
class MyTimer{
	private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
	private Object locker=new Object();
	public  void schedule(Runnable runnable,long delay) {
		synchronized (locker) {
			queue.offer(new MyTimerTask(runnable,delay));
			//这里notify一个可以唤醒两次wait
			//当队列中添加的一个执行之间比队头的时间小的时候就可以唤醒下面的一个wait
			//然后重新计算时间，然后重新进行等待。
			locker.notify();
		}
	}
	public MyTimer() {
		Thread t1=new Thread(()->{
			//这里必须得有一个线程一直进行扫描
			while(true) {
				synchronized (locker) {
					try {
						//不要使用if作为wait的判断条件，
						//如果线程醒了，我们仍然要判断，这个队列是否为空，
						while(queue.isEmpty()) {
							//如果队列为空的话，就要一直进行等待
							locker.wait();
						}
						MyTimerTask tmp=queue.peek();
						long curTime=System.currentTimeMillis();
						if(curTime>tmp.getTime()) {
							//时间到了，就要执行任务
							tmp.getRunnable().run();
							queue.poll();
						} else {
							locker.wait(tmp.getTime()-curTime);
						}
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
			}
		});
		t1.start();
	}
}
 public class Demo19 {
	public static void main(String[] args) {
		MyTimer myTimer=new MyTimer();
		myTimer.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("3333333333333333");
			}
		},3000);
		myTimer.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("2222222222222222");
			}
		},2000);
		myTimer.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("11111111111111111");
			}
		},1000);
		System.out.println("程序启动");
	}
}

